package cn.jcet.module.sys.controller;

import cn.hutool.core.util.IdUtil;
import cn.jcet.common.utils.Constast;
import cn.jcet.common.utils.DataGridView;
import cn.jcet.common.utils.PinyinUtils;
import cn.jcet.common.utils.ResultObj;
import cn.jcet.module.sys.domain.Dept;
import cn.jcet.module.sys.domain.Role;
import cn.jcet.module.sys.domain.User;
import cn.jcet.module.sys.service.IDeptService;
import cn.jcet.module.sys.service.IRoleService;
import cn.jcet.module.sys.service.UserService;
import cn.jcet.module.sys.vo.UserVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.org.apache.regexp.internal.RE;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.xml.crypto.Data;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private IDeptService deptService;

    @Autowired
    private IRoleService roleService;


    /**
     * 查询全部
     * @param userVo
     * @return
     */
    @GetMapping("loadAllUser")
    public DataGridView loadAllUser(UserVo userVo){
        IPage<User> page = new Page<>(userVo.getPage(),userVo.getLimit());

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(userVo.getName()),"loginname",userVo.getName())
                .or().eq(StringUtils.isNotBlank(userVo.getName()),"name",userVo.getName());
        queryWrapper.eq(StringUtils.isNotBlank(userVo.getAddress()),"address",userVo.getAddress());
        queryWrapper.eq("type",Constast.USER_TYPE_NORMAL); //查询系统用户
        queryWrapper.eq(userVo.getDeptid()!=null,"deptid",userVo.getDeptid());
        this.userService.page(page,queryWrapper);
        List<User> userList = page.getRecords();

        for (User user:userList){
            Integer deptId = user.getDeptid();
            if(deptId != null){
                Dept dept = deptService.getById(deptId);
                user.setDeptname(dept.getTitle());
            }

            Integer mgr = user.getMgr();
            if(mgr != null){
                User one = userService.getById(mgr);
                user.setLeadername(one.getName());
            }
        }
        return new DataGridView(page.getTotal(),userList);
    }

    /**
     * 排序最大码
     * @return
     */
    @GetMapping("loadUserMaxOrderNum")
    public Map<String,Object> loadUserMaxOrderNum(){
        //声明map容器
        Map<String,Object> map = new HashMap<>();

        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        //排序
        queryWrapper.orderByDesc("ordernum");
        //分页
        IPage<User> page = new Page<>(1,1);
        List<User> userList = this.userService.page(page, queryWrapper).getRecords();
        if(userList.size() >0){
            map.put("value",userList.get(0).getOrdernum()+1);
        }else {
            map.put("value",1);
        }
        return map;
    }


    /**
     * 根据用户id查询用户
     * @param id
     * @return
     */
    @GetMapping("loadUserById")
    public DataGridView loadUserById(Integer id){
        User user = this.userService.getById(id);

        return new DataGridView(user);
    }

    /**
     * 加载部门id查询用户
     * @param deptId
     * @return
     */
    @GetMapping("loadUsersByDeptId")
    public DataGridView loadUsersByDeptId(Integer deptId){
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(deptId!=null,"deptid",deptId);
        queryWrapper.eq("available",Constast.AVAILABLE_TRUE);
        queryWrapper.eq("type",Constast.USER_TYPE_NORMAL);
        List<User> list = this.userService.list(queryWrapper);
        return new DataGridView(list);
    }

    /**
     * 把中文转换为拼英
     * @param username
     * @return
     */
    @GetMapping("changeChineseToPinyin")
    public Map<String,Object> changeChineseToPinyin(String username){
        Map<String,Object> map = new HashMap<>();

        if (null != username){
            map.put("value",PinyinUtils.getPingYin(username));
        }else {
            map.put("value","");
        }
        return map;
    }

    /**
     * 添加
     * @param userVo
     * @return
     */
    @PostMapping("addUser")
    public ResultObj addUser(UserVo userVo){
        try {
            userVo.setType(Constast.USER_TYPE_NORMAL);//设置类型
            userVo.setHiredate(new Date());
            String salt = IdUtil.simpleUUID().toUpperCase(); //生成随机盐
            userVo.setSalt(salt); //设置盐
            //设置密码
            userVo.setPwd(new Md5Hash(Constast.USER_DEFAULT_PWD,salt,2).toString());
            this.userService.save(userVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }

    /**
     * 修改
     * @param userVo
     * @return
     */
    @PostMapping("updateUser")
    public ResultObj updateUser(UserVo userVo){
        try {
            this.userService.updateById(userVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除
     * @param userVo
     * @return
     */
    @PostMapping("deleteUser")
    public ResultObj deleteUser(UserVo userVo){
        try {
            this.userService.removeById(userVo.getId());
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 重置密码
     * @param id
     * @return
     */
    @PostMapping("resetPwd")
    public ResultObj resetPwd(Integer id){
        try {
            User user = new User();
            user.setId(id);
            String salt = IdUtil.simpleUUID().toUpperCase();
            user.setSalt(salt);//设置盐
            user.setPwd(new Md5Hash(Constast.USER_DEFAULT_PWD,salt,2).toString());
            this.userService.updateById(user);
            return ResultObj.RESET_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.RESET_ERROR;
        }
    }


    @GetMapping("initRoleByUserId")
    public DataGridView initRoleByUserId(Integer id){
        //查询可用对象
        QueryWrapper<Role> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("available",Constast.AVAILABLE_TRUE);
        List<Map<String,Object>> listMaps = this.roleService.listMaps(queryWrapper);

        //查询当前用户拥有的角色ID集合
        List<Integer> currentUserRoleIds = this.roleService.queryUserRoleIdsByUid(id);
        for (Map<String,Object> map:listMaps){
            Boolean LAY_CHECKED=false;
            Integer roleId = (Integer) map.get("id");
            for (Integer rid : currentUserRoleIds){
                if (rid == roleId){
                    LAY_CHECKED = true;
                    break;
                }
            }
            map.put("LAY_CHECKED",LAY_CHECKED);
        }
        return new DataGridView(Long.valueOf(listMaps.size()),listMaps);
    }

    /**
     * 保存用户和角色的关系
     */
    @PostMapping("saveUserRole")
    public ResultObj saveUserRole(Integer uid,Integer[] ids) {
        try {
            this.userService.saveUserRole(uid,ids);
            return ResultObj.DISPATCH_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DISPATCH_ERROR;
        }
    }

    @PostMapping("changePwd")
    public ResultObj doUpdatePassword(String password,String newPwd,String cfgPwd){
        try {
            this.userService.updateUserPwd(password, newPwd, cfgPwd);
            return ResultObj.UPDAREPASSWORD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDAREPASSWORD_ERROR;
        }

    }



}
